package MIPush;

import java.io.IOException;
import java.util.List;

import org.json.simple.parser.ParseException;

import com.xiaomi.xmpush.server.Message;
import com.xiaomi.xmpush.server.Result;
import com.xiaomi.xmpush.server.Sender;

import MIPush.exception.InitDefeatedException;
import cn.westv.scps.utils.PropertiesUtil;

/**
 * 这是执行小米推送的工具类
 * 
 * @author jiawenbin
 *
 */
public class ExecuteMIPush {
	private static ExecuteMIPush instance = new ExecuteMIPush();
	private static Sender androidSender;
	private static Sender iosSender;

	private ExecuteMIPush() {
		init();
	}

	public static ExecuteMIPush newInstance() {
		return instance;
	}

	public static Sender iosSender(){
		return iosSender;
	}
	public static Sender androidSender(){
		return androidSender;
	}
	/**
	 * 执行推送以前，需要进行初始化
	 * 
	 */
	public void init() {
		if (androidSender == null){
			String appSecret = PropertiesUtil.getInstance().getPro("config/app.properties", "MIPush.androidAppSecret");
			androidSender = new Sender(appSecret);
		}
		if(iosSender == null){
			String appSecret = PropertiesUtil.getInstance().getPro("config/app.properties", "MIPush.iosAppSecret");
			iosSender = new Sender(appSecret);
		}
	}

	
	/**
	 * 推送消息,根据账号
	 * 
	 * @throws IOException
	 * @throws ParseException
	 */
	public Result sendToUserAccount(Sender sender, Message message, List<String> accountList, int retries)
			throws IOException, ParseException {
		if (message == null || accountList == null) {
			throw new InitDefeatedException();
		}
		Result res = null;
		if (accountList.size() == 1) {
			res = sender.sendToUserAccount(message, accountList.get(0), retries);
		} else {
			res = sender.sendToUserAccount(message, accountList, retries);
		}
		return res;
	}
	/**
	 * 推送消息,根据别名
	 * 
	 * @throws IOException
	 * @throws ParseException
	 */
	public Result sendToAlias(Sender sender, Message message, List<String> aliasList, int retries)
			throws IOException, ParseException {
		if (message == null || aliasList == null) {
			throw new InitDefeatedException();
		}
		Result res = null;
		if (aliasList.size() == 1) {
			res = sender.sendToAlias(message, aliasList.get(0), retries);
		} else {
			res = sender.sendToAlias(message, aliasList, retries);
		}
		return res;
	}

	
	
	/**
	 * 广播发送消息，给所有设备都发送消息
	 * 
	 * @param message
	 * @param retries
	 * @return
	 * @throws IOException
	 * @throws ParseException
	 */
	public Result broadcastAll(Sender sender, Message message, int retries) throws IOException, ParseException {
		Result broadcastAll = sender.broadcastAll(message, retries);
		return broadcastAll;
	}
}
